<?php

declare(strict_types=1);

namespace Plugin\Attractions\AttractionManagement\Repository;

use App\Repository\IRepository;
use Hyperf\Collection\Arr;
use Hyperf\Collection\Collection;
use Hyperf\Database\Model\Builder;
use Plugin\Attractions\AttractionManagement\Model\Attraction;

class AttractionRepository extends IRepository
{
    public function __construct(protected readonly Attraction $model) {}

    public function handleSearch(Builder $query, array $params): Builder
    {
        return $query
            ->when(Arr::get($params, 'id'), static function (Builder $query, $id) {
                return $query->whereIn('id', Arr::wrap($id));
            })
            ->when(Arr::get($params, 'name'), static function (Builder $query, $name) {
                $query->where('name', 'like', '%' . $name . '%');
            })
            ->when(Arr::get($params, 'introTitle'), static function (Builder $query, $intro_title) {
                $query->where('intro_title', 'like', '%' . $intro_title . '%');
            })
            ->when(Arr::get($params, 'status'), static function (Builder $query, $status) {
                $query->where('status', $status);
            });
    }

    public function showListPage(array $params = []): array
    {
        $page = intval(Arr::get($params, 'page', 1));
        $pageSize = intval(Arr::get($params, 'page_size', 20));
        return $this->perQuery($this->getQuery(), $params)
            ->simplePaginate($pageSize, ['id', 'name', 'intro_title as introTitle', 'cover_id as coverId', 'status', 'address', 'phone', 'open_time as openTime', 'close_time as closeTime'], 'page', $page)
            ->items();
    }

    public function detail(int $id): array
    {
        return $this->getQuery()
            ->where('id', $id)
            ->get(['id', 'name', 'intro_title as introTitle', 'intro', 'cover_id as coverId', 'status', 'address', 'phone', 'open_time as openTime', 'close_time as closeTime'])
            ->firstOrFail()
            ->toArray();
    }
}
